<script lang="ts" setup>
import { CascaderConfig, FormInstance } from "element-plus";
import { CascaderOption } from "element-plus/lib/components/index.js";
import { computed, nextTick, reactive, ref, toRaw, watch } from "vue";
import { listTaskType } from "../api/listTaskType";
import { useTypeListStore } from "../store/typeListStore";
import { getTaskDetail } from "../api/task";
import { BuildTaskRecord } from "../model";

const props = defineProps<{
  visible: boolean;
  data?: Partial<BuildTaskRecord>;
}>();

const cascaderOptions = ref<CascaderOption[]>([]);
const { setData, getTypeName } = useTypeListStore();
const formRef = ref<FormInstance>();
const loading = ref(false);
const taskDetail = ref<BuildTaskRecord | null>(null);
const cascaderProps: Partial<CascaderConfig> = {
  multiple: true,
};
const emit = defineEmits(["update:visible", "ok"]);
const form = reactive({
  taskTitle: "",
  taskDesc: undefined,
  taskList: [] as { type: string; total: number }[],
});

const cascaderData = computed(() => {
  if (taskDetail.value) {
    return taskDetail.value.taskList.map((v) => {
      return [
        v.type.includes("element-plus") ? "WithElementPlus" : "Basic",
        v.type,
      ];
    });
  }
  return [];
});

const handleCascaderChange = (checkedList: any) => {
  const oldList = form.taskList;
  form.taskList = checkedList.map((v: string[]) => {
    const type = v[v.length - 1];
    const oldTotal = oldList.find((val) => val.type === type)?.total;
    return {
      type,
      total: oldTotal || 6,
    };
  });
};

const refreshTaskDetail = () => {
  if (loading.value) return;
  loading.value = true;
  getTaskDetail(props.data?.taskId || "")
    .then((res) => {
      taskDetail.value = res;
      Object.assign(form, {
        taskTitle: res?.taskTitle,
        taskDesc: res?.taskDesc,
        taskList: res?.taskList || [],
      });
    })
    .catch((e) => {
      console.error(e);
      ElMessage.error("详情查询失败");
    })
    .finally(() => {
      loading.value = false;
    });
};

const handleCancel = () => {
  emit("update:visible", false);
};

const handleOk = () => {
  formRef.value
    ?.validate()
    .then(() => {
      emit("ok", toRaw(form));
    })
    .catch(() => {});
};

watch(
  () => props.visible,
  (v) => {
    if (v) {
      taskDetail.value = null;
      if (props.data) {
        refreshTaskDetail();
      } else {
        Object.assign(form, {
          taskTitle: "",
          taskDesc: undefined,
          taskList: [] as { type: string; total: number }[],
        });
      }
      setTimeout(() => {
        formRef.value?.clearValidate();
      }, 10);
    }
  },
  {
    immediate: true,
  }
);

const init = () => {
  listTaskType().then((v) => {
    cascaderOptions.value = v.tree;
    setData(v.data);
  });
};

init();
</script>

<template>
  <el-dialog
    title="创建构建任务"
    :model-value="visible"
    @update:model-value="handleCancel"
    :close-on-click-modal="false"
  >
    <el-form
      v-loading="loading"
      :size="'small'"
      ref="formRef"
      :model="form"
      :label-width="80"
    >
      <el-form-item
        :rules="[{ required: true, message: '标题必填' }]"
        label="任务标题"
        prop="taskTitle"
      >
        <el-input
          size="small"
          placeholder="请输入"
          v-model="form.taskTitle"
        ></el-input>
      </el-form-item>
      <el-form-item label="任务描述">
        <el-input
          size="small"
          placeholder="请输入"
          :type="'textarea'"
          :autosize="{ maxRows: 4, minRows: 2 }"
          v-model="form.taskDesc"
        ></el-input>
      </el-form-item>
      <el-form-item
        :rules="[
          {
            required: true,
            validator: (_, value, cb) => {
              if (value.length) cb();
              else cb(new Error('任务类型必选'));
            },
          },
        ]"
        label="任务类型"
        prop="taskList"
      >
        <el-cascader
          size="small"
          style="width: 100%"
          :options="cascaderOptions"
          :props="cascaderProps"
          :show-all-levels="false"
          :model-value="cascaderData"
          @update:model-value="handleCascaderChange"
          @clear="handleCascaderChange([])"
          clearable
          collapse-tags
        />
      </el-form-item>
    </el-form>
    <el-table
      size="small"
      v-loading="loading"
      max-height="400"
      style="margin-top: 16px"
      :data="form.taskList"
      :highlight-current-row="false"
    >
      <el-table-column label="任务类型" prop="type" min-width="160px">
        <template #default="{ row }">
          {{ getTypeName(row.type) }}
        </template>
      </el-table-column>
      <el-table-column
        label="执行次数"
        prop="total"
        :min-width="200"
        :align="'right'"
      >
        <template #default="{ row }">
          <el-input-number
            size="small"
            placeholder="请输入执行次数"
            v-model="row.total"
            :min="1"
            :max="20"
            style="width: 200px"
          ></el-input-number>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button size="small" @click="handleCancel">取消</el-button>
      <el-button size="small" type="primary" @click="handleOk">确定</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.item-wrap {
  max-height: 500px;
  overflow: auto;
}
</style>
